<template>
  <div v-loading="loading">
    <TableSearch
      ref="tableSearch"
      :search-path="searchPath"
      :tableBtns="tableBtns"
      :formItemsInline="formItemsInline"
      :columns="columns"
      :tableData="tableData"
      :form="form"
      @handleTableData="handleTableData"
      @reset="reset"
    >
      <template slot="address">
        <el-form-item>
          <HycAddressCascader ref="area" v-model="area" />
        </el-form-item>
      </template>
    </TableSearch>
    <EditDeviceThreshold
      @refreshTable="refreshTable"
      :visible.sync="editDeviceThresholdVisible"
      :option-attr="optionAttr"
      :type="'station'"
    />
    <InsuranceSet
      :visible.sync="viewInsuranceSetVisible"
      :stationId="stationId"
    >
    </InsuranceSet>
  </div>
</template>

<script>
import TableSearch from '@/components/TableSearch'
import HycAddressCascader from '@/components/hycAddressCascader'
import EditDeviceThreshold from './components/EditDeviceThreshold'
import InsuranceSet from './components/InsuranceSet'
import { exportExcel } from '@/utils'
import {
  stationList,
  exportStationList,
  deleteStation,
  enableStation,
  exportStation,
  stationVersionUp,
} from '@/api/device'
import formatter from '@/utils/format'
export default {
  name: 'StationList',
  components: {
    TableSearch,
    HycAddressCascader,
    EditDeviceThreshold,
    InsuranceSet,
  },
  data() {
    return {
      stationId: -1,
      loading: true,
      optionAttr: {},
      editDeviceThresholdVisible: false,
      viewInsuranceSetVisible: false,
      form: {
        stationName: '',
        mchName: '',
        city: null,
        district: null,
        province: null,
      },
      area: {},
      searchPath: '/web/device-management/station-management/查询',
      tableBtns: [
        {
          label: '导出',
          isExport: true,
          resourceId: '/web/device-management/station-management/电站导出',
          startDownload: (callback) => {
            let params = Object.assign(
              {},
              {
                ...this.form,
                pageSize: 10,
                currentPage: 1,
              },
              this.area.city && { city: this.area.city },
              this.area.district && { district: this.area.district },
              this.area.province && { province: this.area.province }
            )
            exportStationList(params)
              .then((res) => {
                callback(res)
              })
              .catch((err) => {
                console.log(err)
              })
          },
        },
        {
          label: '一键设置保险费',
          resourceId:
            '/web/device-management/station-management/一键设置保险费',
          click: () => {
            this.viewInsuranceSetVisible = true
            this.stationId = 0 // 一键设置电站为0
          },
        },
      ],
      formItemsInline: [
        {
          slot: 'address',
        },
        {
          type: 'text',
          value: 'stationName',
          placeholder: '请输入电站名关键字',
          clearable: true,
          resourceId: '/web/device-management/station-management/充电站名',
        },
        {
          type: 'text',
          value: 'mchName',
          placeholder: '请输入运营商关键字',
          clearable: true,
          resourceId: '/web/device-management/station-management/所属代理商',
        },
      ],
      tableData: {},
      columns: [
        {
          label: '创建日期',
          prop: 'createTime',
          width: '200px',
          formatter,
          resourceId: '/web/device-management/station-management/创建日期',
        },
        {
          label: '所在地区',
          prop: 'provinceName',
          resourceId: '/web/device-management/station-management/所在地区',
          // formatter: (row) => filter('provinceToName')(row.province),
        },
        {
          label: '充电站名',
          prop: 'stationName',
          resourceId: '/web/device-management/station-management/充电站名',
        },
        {
          label: '地址描述',
          prop: 'stationAddress',
          width: '400px',
          resourceId: '/web/device-management/station-management/地址描述',
          // formatter: (row) => filter('limitTo')(row.staaddress, 25),
        },
        {
          label: '停用状态',
          prop: 'unableCyclesStatusDesc',
          resourceId: '/web/device-management/station-management/停用状态',
        },
        {
          label: '包含充电口',
          prop: 'plug',
          resourceId: '/web/device-management/station-management/包含充电口',
        },
        {
          label: '所属运营商',
          prop: 'mchName',
          resourceId: '/web/device-management/station-management/所属代理商',
        },
        {
          label: '设置参数',
          prop: 'configId',
          resourceId: '/web/device-management/station-management/设置参数',
          formatter: (row) => (row.configId === 1 ? '默认设置' : '自定义设置'),
        },
        {
          label: '充电站ID',
          prop: 'id',
          resourceId: '/web/device-management/station-management/充电站ID',
        },
        {
          label: '操作',
          width: '500px',
          resourceId: '/web/device-management/station-management/操作',
          buttons: [
            {
              label: '设置保险费',
              size: 'small',
              resourceId:
                '/web/device-management/station-management/设置保险费',
              click: (row) => {
                this.viewInsuranceSetVisible = true
                this.stationId = row.id
              },
              ifRender: (row) => {
                return row.insurStation == true
              },
            },
            {
              label: '详情',
              size: 'small',
              resourceId: '/web/device-management/station-management/详情',
              click: (row) => {
                this.$router.push({
                  path: `/device/stationDetail/${row.id}`,
                })
              },
            },
            {
              label: '导出',
              size: 'small',
              resourceId: '/web/device-management/station-management/导出',
              click: (row) => {
                exportStation({
                  stationId: row.id,
                }).then((res) => {
                  exportExcel(res, '电站设备信息')
                })
              },
              // startDownload: (callback, row) => {
              //   exportStation({
              //     id: row.id,
              //     currentPage: 1,
              //     pageSize: 10,
              //   })
              //     .then((res) => {
              //       callback(res)
              //     })
              //     .catch((err) => {
              //       console.log(err)
              //       callback(0)
              //     })
              // },
              // click: this.handleExport,
            },
            {
              label: '删除',
              size: 'small',
              resourceId: '/web/device-management/station-management/删除',
              click: this.handleDelete,
              // ifRender: (row) => {
              //   return row.stationUserId === this.userId
              // },
            },
            {
              label: '参数设置',
              size: 'small',
              resourceId: '/web/device-management/station-management/参数设置',
              click: (row) => {
                this.editDeviceThresholdVisible = true
                this.optionAttr = row
              },
            },
            {
              label: '停用',
              size: 'small',
              resourceId: '/web/device-management/station-management/启用/停用',
              click: this.handleStatus,
              ifRender: (row) => {
                return row.status === 'NORMAL'
              },
            },
            {
              label: '启用',
              size: 'small',
              resourceId: '/web/device-management/station-management/启用/停用',
              click: this.handleStatus,
              ifRender: (row) => {
                return row.status === 'STOP'
              },
            },
            {
              label: '停用管理',
              size: 'small',
              resourceId: '/web/device-management/station-management/停用管理',
              disabled: (row) => {
                return row.status === 'STOP'
              },
              // ifRender: (row) => {
              //   return row.stationUserId === this.userId
              // },
              click: (row) => {
                this.$router.push({
                  path: `/device/cycleManagement/${row.id}`,
                })
              },
            },
            {
              label: '复制',
              size: 'small',
              resourceId: '/web/device-management/station-management/复制',
              // ifRender: (row) => {
              //   return row.stationUserId === this.userId
              // },
              click: (row) => {
                this.$router.push({ path: `/device/copy/${row.id}` })
              },
            },
            {
              label: '升级',
              size: 'small',
              class: 'table-button-green',
              resourceId: '/web/device-management/station-management/升级',
              click: this.handleUpgrade,
            },
          ],
        },
      ],
    }
  },
  // computed: {
  //   userId() {
  //     return this.$store.getters.userId
  //   },
  // },
  methods: {
    reset() {
      this.form = {
        stationName: '',
        mchName: '',
        city: null,
        district: null,
        province: null,
      }
      this.area = {}
    },
    handleTableData(params) {
      this.loading = true
      params = { ...params, ...this.area }
      if (this.$route?.query?.id) {
        params.mchIds = this.$route.query.id
      }
      stationList(params).then(
        (res) => {
          this.loading = false
          this.tableData = {
            list: res.list,
            totalCount: res.totalAmount,
          }
        },
        () => {
          this.loading = false
        }
      )
    },
    refreshTable() {
      this.$refs.tableSearch.refreshTable()
    },
    handleDelete(row) {
      this.$confirm(`您确定要删除${row.stationName}的电站吗？`, '提示', {
        center: true,
        customClass: 'tip-dialog__wrapper',
      })
        .then(() => {
          deleteStation({
            id: row.id,
          }).then(() => {
            this.$message({
              message: '删除成功',
              type: 'success',
            })
            this.refreshTable()
          })
        })
        .catch((err) => console.log(err))
    },
    handleStatus(row) {
      this.$confirm(
        `您确定要${row.status === 'STOP' ? '启用' : '停用'}${
          row.stationName
        }的电站吗？`,
        '提示',
        {
          center: true,
          customClass: 'tip-dialog__wrapper',
        }
      )
        .then(() => {
          enableStation({
            id: row.id,
            status: row.status === 'STOP' ? 'NORMAL' : 'STOP',
          }).then(() => {
            this.$message({
              message: '操作成功',
              type: 'success',
            })
            this.refreshTable()
          })
        })
        .catch((err) => console.log(err))
    },
    handleUpgrade(row) {
      const loading = this.$loading({
        lock: true,
        text: '操作进行中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)',
      })
      stationVersionUp({ stationIds: [row.id] }).then(
        () => {
          loading.close()
          this.$message({
            type: 'success',
            message: '指令下发成功，跳转升级结果页面',
          })
          this.$router.push('/device/upgrade')
        },
        () => {
          loading.close()
        }
      )
    },
  },
}
</script>
